<template>
  <div class="app-container addProjectApp">
    <div class="type">
          <el-breadcrumb separator-class="el-icon-arrow-right">
                <!-- <el-breadcrumb-item :to="{path:'/entry',name:'entry',params:{courseId:courseId}, query:{anchor:anchor,type:1}}">课程建设</el-breadcrumb-item> -->
                <el-breadcrumb-item :to="{path:'/project/projectList'}" style="font-size: 16px;color: #262626;">项目管理</el-breadcrumb-item>
                <el-breadcrumb-item :to="{path:'/project/projectList'}" style="font-size: 12px;color: #777777 !important;line-height:52px">项目列表</el-breadcrumb-item>
                <el-breadcrumb-item style="font-size: 12px;color: #777777 !important;line-height:52px">{{id==0?'新建项目':'编辑项目'}}</el-breadcrumb-item>
            </el-breadcrumb>
       </div>
       <div class="header">
            <!-- <h3 >{{id==0?'新建项目':'编辑项目'}}</h3> -->
            <div class="navList clearfloat">
               <h4 class="h5 clearfloat">
                 <img src="../../assets/img/xiangmuming.png" style="float:left;"/>
                 <span style="float:left;">项目名称</span>
               </h4>
               <el-input v-model="projectName" ref="projectName" class="input" placeholder="请填写项目名称，4~20个字，必填项" @blur="validateMobileName"></el-input>
               <div class="uploadFontFont">
                  <div class="xing">*</div>
              </div>
            </div>
            <div class="navList clearfloat">
               <!-- <h4 class="h5"></h4> -->
                <h4 class="h5 clearfloat">
                 <img src="../../assets/img/xiangq.png" style="float:left;"/>
                 <span style="float:left;">项目地址</span>
               </h4>
               <el-input v-model="projectAddress" id="keyword" name="keyword"  class="input" placeholder="请输入项目地址，必填项" @focus='projectAddress=""' @blur="validateMobileAddress"></el-input>
               <div class="uploadFontFont">
                  <div class="xing">*</div>
              </div>
               <!-- <input v-model="projectAddress" id="keyword" name="keyword"  class="input" placeholder="请输入项目地址，必填项" @focus='projectAddress=""'/> -->
               <div class="mapContainer">
                  <div id="mapContainer"></div>
               </div>
            </div>
            <div class="navList clearfloat">
              <!-- xiangmu.png -->
               <!-- <h4 class="h5">项目详情</h4> -->
               <h4 class="h5 clearfloat">
                 <img src="../../assets/img/xiangmu.png" style="float:left;"/>
                 <span style="float:left;">项目详情</span>
               </h4>
               <el-input v-model="projectDetail" ref="projectDetail" type="textarea" class="input textarea" placeholder="请输入项目详情，1~1000字，必填项" @blur="validateMobileDetail"></el-input>
               <div class="uploadFontFont">
                  <div class="xing">*</div>
              </div>
            </div>
            <div class="navList clearfloat">
               <!-- <h4 class="h5">项目主图</h4> -->
                <h4 class="h5 clearfloat">
                 <img src="../../assets/img/zhutu.png" style="float:left;"/>
                 <span style="float:left;">项目主图</span>
               </h4>
               <!-- <el-input v-model="projectAddress" class="input" placeholder="请输入项目地址，必填项"></el-input> -->
               <div class="uploadDetail clearfloat">
                 <Upload :limit='1' :height="548"  style="float:left;" @uploadHandler='uploadChange' :dataHome='fileHomePic'></Upload> 
               </div>
            </div>
            <div class="navList clearfloat">
               <!-- <h4 class="h5">项目大图</h4> -->
               <h4 class="h5 clearfloat">
                 <img src="../../assets/img/datu.png" style="float:left;"/>
                 <span style="float:left;">项目大图</span>
               </h4>
               <!-- <el-input v-model="projectAddress" class="input" placeholder="请输入项目地址，必填项"></el-input> -->
               <div class="uploadDetail clearfloat">
                 <!-- <div class="upload">+ 上传</div> -->
                 <Upload :limit='50' :height="548" style="float:left;" @uploadHandler='uploadChange' :dataOther='fileOtherPic'></Upload> 
                
               </div>
            </div>
            <div class="navList clearfloat">
               <!-- <h4 class="h5">联系电话</h4> -->
               <h4 class="h5 clearfloat">
                 <img src="../../assets/img/lianxi.png" style="float:left;"/>
                 <span style="float:left;">联系电话</span>
               </h4>
               <input type="text" v-model="projectPhone" class="input el-input__inner" ref="projectPhone" placeholder="请输入联系电话，必填项" @blur="validateMobilePhone" />
               <div class="uploadFontFont">
                  <div class="xing">*</div>
               </div>
            </div>
            <div class="navList clearfloat">
               <!-- <h4 class="h5">配套设置</h4> -->
                <h4 class="h5 clearfloat">
                 <img src="../../assets/img/peizhi.png" style="float:left;"/>
                 <span style="float:left;">配套设置</span>
               </h4>
               <div class="checkDetail clearfloat">
                 <div class="checkListAll clearfloat">
                   <span>基础设施（必填）</span>
                   <el-checkbox-group v-model="checkListBase" class="checkList checkListNew">
                    <el-checkbox :value="item.code" :label="item.desc" v-for="(item,index) in basicFacility" :key=index></el-checkbox>
                  </el-checkbox-group>
                 </div>
                 <div class="checkListAll clearfloat">
                   <span>餐饮服务（必填）</span>
                   <el-checkbox-group v-model="checkListEat" class="checkList checkListNew" >
                     <el-checkbox :value="item.code" :label="item.desc" v-for="(item,index) in catering" :key=index></el-checkbox>
                  </el-checkbox-group>
                 </div>
                 <div class="checkListAll clearfloat">
                   <span>娱乐活动（必填）</span>
                   <el-checkbox-group v-model="checkListPlay" class="checkList checkListNew">
                     <el-checkbox :value="item.code" :label="item.desc" v-for="(item,index) in recreation" :key=index></el-checkbox>
                  </el-checkbox-group>
                 </div>
               </div>
            </div>
            <div class="sumitAdd clearfloat">
              <!-- <router-link :to="{path:'/project/projectList'}"> -->
                  
              <!-- </router-link> -->
              <div class="sumitBtn setData" @click="addProjectData">提交</div>
              <div class="sumitBtn" @click="sumitBtnFalse">取消</div>
            </div>
       </div>
       <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="370px"
       >
        <span>是否确认离开，所做的修改将不被保存</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureBtn()">确 定</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
import api from "../../fetch/url";
import axios from "axios";
import Upload from '@/components/upload';
export default {
  components:{
    Upload,
  },
  data() {
    return {
       dialogVisible:false,
       projectName:"",
       projectAddress:"",
       projectDetail:"",
       projectPhone:"",
       checkListBase:[],
       checkListEat:[],
       checkListPlay:[],
       checkListBase2:[],
       checkListEat2:[],
       checkListPlay2:[],
       fileHomePic:{},//项目主图
       fileOtherPic:[],//项目图片
       basicFacility:[],
       recreation:[],
       catering:[],
       id:this.$route.params.id,
       marker:null,
       loca:{
         name:null,
         location:{
           R:"",
           Q:"",
           lng:"",
           lat:""
         }
       },
       map:null,
       projectDto:{
        basicFacility: [0],  //基础设施
        catering: [0],//餐饮服务
        detail: "",  //项目详情
        homePic: {   //项目主图
          bucket: "string",
          fileKey: "string",
          name: "string"
        },
        id: 0,
        location: {  //项目地址
          address: "",
          latitude: "",
          longitude: ""
        },
        name: "",  //项目名称
        othersPic: [  //项目图片 
            {
              bucket: "string",
              fileKey: "string",
              name: "string"
        }],
        recreation: [0],  //娱乐活动
        tel: ""  //联系电话
      }
    }
  },
  created() {
    //enumsAll
    api.enumsAll({},{
      headers: {
          'Content-Type': 'application/json;charset=UTF-8'
      }
    }).then(json => {
      if(json){
        this.basicFacility=json.basicFacility;
        this.recreation=json.recreation;
        this.catering=json.catering;
        if(this.id!=0){  //编辑状态
            //projectIdDetail
            api.projectIdDetail({},this.id,{
              headers: {
                  'Content-Type': 'application/json;charset=UTF-8'
              }
            }).then(json => {
              if(json){
                this.fileOtherPic = json.othersPic;
                this.fileHomePic = json.homePic;
                this.projectName=json.name;
                this.projectAddress=json.geoLocation.address;
                this.addMarker(json.geoLocation.longitude+"",json.geoLocation.latitude+"");
                this.map.setZoomAndCenter(14, [json.geoLocation.longitude+"",json.geoLocation.latitude+""]); //同时设置地图层级与中心点

                this.loca.name=this.projectAddress;
                this.loca.location.lat=json.geoLocation.latitude;
                this.loca.location.lng=json.geoLocation.longitude;
                this.projectDetail=json.detail;
                this.projectPhone=json.tel;
                if(json.basicFacility.length==0){
                    this.checkListBase=json.basicFacility;
                }else {
                    this.checkListBase=[];
                    for(let i in this.basicFacility){
                      for(let j in json.basicFacility){
                          if(this.basicFacility[i].code==json.basicFacility[j]){
                              this.checkListBase.push(this.basicFacility[i].desc);
                          }
                      } 
                    }
                }
                if(json.catering.length==0){
                    this.checkListEat=json.catering;
                }else {
                  this.checkListEat=[];
                    for(let i in this.catering){
                      for(let j in json.catering){
                          if(this.catering[i].code==json.catering[j]){
                              this.checkListEat.push(this.catering[i].desc);
                          }
                      } 
                    }
                }
                if(json.recreation.length==0){
                    this.checkListPlay=json.recreation;
                }else {
                  this.checkListPlay=[];
                    for(let i in this.recreation){
                      for(let j in json.recreation){
                          if(this.recreation[i].code==json.recreation[j]){
                              this.checkListPlay.push(this.recreation[i].desc);
                          }
                      } 
                    }
                }
              }
            });
          }
      }
    });
  },
  mounted() {
      this.init();
      if(this.id==0){
         document.title = "新建项目 - 阅阳旅居";
      }else {
          document.title = "编辑项目 - 阅阳旅居";
      }
  },
  methods: {
      sumitBtnFalse(){
        this.dialogVisible=true;
      },
      //点击弹框中的确定按钮
      sureBtn(){
          this.$router.push({
            path:'/project/projectList',
            name:'projectList',
          })
      },
      uploadChange(fileInfo,type){
        if(type == 1){//项目主图
            this.fileHomePic = fileInfo;
        }else if(type == -1){
            this.fileOtherPic.splice(fileInfo,1);
        }else{//项目图片
            this.fileOtherPic.push(fileInfo);
        }
      },
      scrollFunc(event){
          let evt = event || window.event;  
          if(evt.preventDefault) {  
          // Firefox  
            evt.preventDefault();  
            evt.stopPropagation();  
          } else {  
            // IE  
            evt.cancelBubble=true;  
            evt.returnValue = false;  
        }  
        return false;
      },
      //提交的时候获取配套设施需要提交给后台的数据
      changeBaseEatPlay(){
          this.checkListBase2=[];
          for(let i in this.checkListBase){
            for(let j in this.basicFacility){
                if(this.checkListBase[i]==this.basicFacility[j].desc){
                      this.checkListBase2.push(this.basicFacility[j].code);
                }
            } 
          }
          this.checkListEat2=[];
          for(let i in this.checkListEat){
            for(let j in this.catering){
                if(this.checkListEat[i]==this.catering[j].desc){
                      this.checkListEat2.push(this.catering[j].code);
                }
            } 
          }
          this.checkListPlay2=[];
          for(let i in this.checkListPlay){
            for(let j in this.recreation){
                if(this.checkListPlay[i]==this.recreation[j].desc){
                      this.checkListPlay2.push(this.recreation[j].code);
                }
            } 
          }
          console.log(this.checkListBase2,this.checkListEat2,this.checkListPlay2,9999);
      },
      //点击提交按钮
      addProjectData(){
        //提交时的校验
        if(this.sumitCheck() ==false){
          return false;
        }
        this.changeBaseEatPlay();
        if(this.id==0){  //新建
            //projectAdd
            api.projectAdd({
                basicFacility: this.checkListBase2,  //基础设施
                catering: this.checkListEat2,//餐饮服务
                detail: this.projectDetail,  //项目详情
                homePic: this.fileHomePic,
                id: 0,
                location: {
                  address: this.loca.name,
                  latitude: this.loca.location.lat,
                  longitude: this.loca.location.lng
                },
                name: this.projectName,  //项目名称
                othersPic: this.fileOtherPic,
                recreation: this.checkListPlay2,  //娱乐活动
                tel: this.projectPhone //联系电话
            }).then(json => {
               this.$message({
                message: "项目创建成功",
                type: "success",
              });
              // console.log(json,9999);
              setTimeout(()=>{
                  this.$router.push({
                  path:'/project/detailProject',
                  name:'detailProject',
                  params: {
                    id: json
                  }
                })
              },1000)
               
            });
        }else {  //编辑
            // console.log(this.projectAddress,this.loca.name,889898989);
            if(this.projectAddress!=this.loca.name){  
                this.$message({
                    message: "项目地址请选择合法的并且详细的地址",
                    type: "error",
                });
                return false;
            }
            api.projectEdit({
                basicFacility: this.checkListBase2,  //基础设施
                catering: this.checkListEat2,//餐饮服务
                detail: this.projectDetail,  //项目详情
                homePic: this.fileHomePic,
                id: this.id,
                location: {
                  address: this.loca.name,
                  latitude: this.loca.location.lat,
                  longitude: this.loca.location.lng
                },
                name: this.projectName,  //项目名称
                othersPic: this.fileOtherPic,
                recreation: this.checkListPlay2,  //娱乐活动
                tel: this.projectPhone //联系电话
            }).then(json => {
                this.$message({
                  message: "项目编辑成功",
                  type: "success",
                });
                setTimeout(()=>{
                    this.$router.push({
                    path:'/project/detailProject',
                    name:'detailProject',
                  })
                },1000)
            });
        }
      },
      //提交时的校验
      sumitCheck(){
          //项目名称，4~20个字，必填项
          if(this.projectName==""){
            this.$message({
                  message: "项目名称不能为空",
                  type: "error",
              });
              return false;
          }
          //项目地址
          if(this.projectAddress==""){
               this.$message({
                  message: "项目地址不能为空",
                  type: "error",
              });
              return false;
          }else {
                if(this.loca.name==null||this.loca.name==""||this.loca.location==""){  //此时没有坐标
                        this.$message({
                            message: "项目地址请选择合法的并且详细的地址",
                            type: "error",
                        });
                        this.projectAddress="";
                        return false;
                }
            }
          //项目详情 
           if(this.projectDetail==""){
                this.$message({
                  message: "项目详情不能为空",
                  type: "error",
               });
              return false;
            }
              //项目主图不能为空
          if(JSON.stringify(this.fileHomePic) == "{}"){
            this.$message.closeAll();
              this.$message({
                  message: "项目主图不能为空",
                  type: "error",
              });
              return false;
          }
          
            //项目大图不能为空
          if(this.fileOtherPic.length == 0){
            this.$message.closeAll();
              this.$message({
                  message: "项目大图不能为空",
                  type: "error",
              });
              return false;
          }

          //联系电话
          if(this.projectPhone==""){
              this.$message({
                  message: "联系电话不能为空",
                  type: "error",
              });
              return false;
          }
          
          //

          if(this.checkListBase.length==0){
            this.$message({
                  message: "基础设施至少选择一项",
                  type: "error",
              });
              return false;
          }
          if(this.checkListEat.length==0){
            this.$message({
                  message: "餐饮服务至少选择一项",
                  type: "error",
              });
              return false;
          }
          if(this.checkListPlay.length==0){
            this.$message({
                  message: "娱乐活动至少选择一项",
                  type: "error",
              });
              return false;
          }
          return true;
      },
      //项目地址失去焦点
      validateMobileAddress(){
       
      },
      //项目详情失去焦点
      validateMobileDetail(){
            if(this.projectDetail.length-1000>0){  //大于1000个字
                this.$message({
                    message: "项目详情必须为1~1000个字",
                    type: "error",
                });
                this.$refs.projectDetail.focus();
                // this.projectDetail=this.projectDetail.substr(0,1000);
                return false;
            }
      },
      //项目名称失去焦点校验
      validateMobileName(){
           if(this.projectName.length<4||this.projectName.length>20){
              this.$message({
                  message: "项目名称必须4~20个字",
                  type: "error",
              });
              // this.projectName="";
              this.$refs.projectName.focus();
              return false;
            }
      },
      //初始化代码
      init(){
          this.map = new AMap.Map("mapContainer", {
              resizeEnable: true,
              center: ['118.397428','39.90923'],//地图中心点
              zoom: 11,//地图显示的缩放级别
              keyboardEnable: false
          });
          this.loca.name = null;
          // var marker = null;
          AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'],()=>{
              var autoOptions = {
                  city: "北京", //城市，默认全国
                  input: "keyword"//使用联想输入的input的id
              };
              let autocomplete= new AMap.Autocomplete(autoOptions);
              var placeSearch = new AMap.PlaceSearch({
                  city:'北京',
                  map:this.map
              });
              AMap.event.addListener(autocomplete, "select", (e)=>{
                  //TODO 针对选中的poi实现自己的功能
                  console.log(e.poi);
                  this.loca = e.poi;
                  this.loca.name=e.poi.district+e.poi.name;
                  this.projectAddress=this.loca.name;
                  this.addMarker(this.loca.location.R,this.loca.location.Q);
                  this.map.setZoomAndCenter(14, [this.loca.location.R,this.loca.location.Q]); //同时设置地图层级与中心点
                  if(this.loca.location==""){  //此时没有坐标

                  }else {  //存在坐标
                     console.log(this.loca.location.lng,this.loca.location.lat,"坐标地址");
                  }

              });
          });
          if (typeof this.map !== 'undefined') {
              this.map.on('complete', function() {
                if (location.href.indexOf('guide=1') !== -1) {
                  this.map.setStatus({
                    scrollWheel: false
                  });
                  if (location.href.indexOf('litebar=0') === -1) {
                    this.map.plugin(["AMap.ToolBar"], function() {
                      var options = {
                        liteStyle: true
                      }
                      if (location.href.indexOf('litebar=1') !== -1) {
                        options.position = 'LT';
                        options.offset = new AMap.Pixel(10, 40);
                      } else if (location.href.indexOf('litebar=2') !== -1) {
                        options.position = 'RT';
                        options.offset = new AMap.Pixel(20, 40);
                      } else if (location.href.indexOf('litebar=3') !== -1) {
                        options.position = 'LB';
                      } else if (location.href.indexOf('litebar=4') !== -1) {
                        options.position = 'RB';
                      }
                      this.map.addControl(new AMap.ToolBar(options));
                    });
                  }
                }
          });
        }
      },
       // 实例化点标记
      addMarker(R,Q) {
          this.clearMarker();
          this.marker = new AMap.Marker({
              icon: "",
              position: [R,Q],
              offset: new AMap.Pixel(-13, -30)
          });
          this.marker.setMap(this.map);
      },
      // 清除 marker
      clearMarker() {
          if (this.marker) {
              this.marker.setMap(null);
              this.marker = null;
          }
      },
      //手机号码验证
			validateMobilePhone(){
        console.log(this.projectPhone);
				if(this.projectPhone!=''){
					if(!(/^1[34578]\d{9}$/.test(this.projectPhone))&&!/^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/.test(this.projectPhone)) {
						this.projectPhone="";
            this.$message({
                  message: "联系电话格式错误",
                  type: "error",
              });
						this.$refs.projectPhone.focus();
					}
				}
      },
      
  }
}
</script>
<style lang="scss">
.el-pagination.is-background .btn-next, .el-pagination.is-background .btn-prev, .el-pagination.is-background .el-pager li {
  background-color: #fff;
}

.textarea .el-textarea__inner{ 
  resize: none;
  height: 128px;
}
.checkListNew .el-checkbox{
   width:100px;
}
.app-container .el-form-item.is-success .el-input__inner,.app-container  .el-form-item.is-success .el-textarea__inner{
  border: 1px solid #DDDDDD !important;
  background-color: #fff !important;
  background: #fff !important;
}
.app-container .el-form-item.is-success .el-input__inner:focus,.app-container .el-form-item.is-success .el-textarea__inner:focus,.app-container .el-input.is-active .el-input__inner,.app-container .el-input__inner:focus {
  border: 1px solid #FF6A00 !important;
  border-color:#FF6A00 !important;
      background-color: #fff !important;
    background: #fff !important;
}
.el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color:#FC612A !important;
  border-color:#FC612A !important;
}
.el-checkbox__input.is-checked+.el-checkbox__label,.el-textarea__inner:focus,.el-textarea__inner:focus {
  border-color:#FC612A !important;
}
.addProjectApp {
  .el-breadcrumb{
    hieght:52px;
    line-height:52px;
  }
}
</style>
<style lang="scss" scoped>
  .app-container {
    padding:16px 24px 35px;
  }
  .addProjectApp {
     .type {
         padding:0px 30px 10px 0px;border-bottom:1px solid #E5E7EB;height:52px;line-height:52px;
     }
  }
  .header {
       width: 100%;
      border-radius:4px;
      background: #fff;
      // padding:0px 20px;
      box-sizing: border-box;
      .navList {
          padding:20px 0 0 0;
          box-sizing: border-box;
          .h5,.input {
            float: left;
          }
          .h5 {
            width:100px;
            height: 40px;
            line-height: 40px;
            font-size: 14px;
            color: #262626;
            img {
              // width:14px;
              margin-top:13px;
              margin-right:10px;
            }
            span {
              font-size: 14px;
              color: #262626;
            }
          }
          .input {
            width:80%;
          }
          .uploadDetail {
            float: left;
            width:74%;
             .upload {
               width:150px;
               height: 115px;
               border: 1px solid #DCDFE6;
               border-radius: 4px;
               text-align: center;
               line-height: 115px;
               color: #ccc;
               cursor: pointer;
             }
             p {
               margin-top:5px;
               color: #ccc;
               font-size:14px;
             }
          }
          .checkDetail {
            float: left;
            width:80%;
            background: #F7F7F9;
            border-radius: 2px;
            padding:8px 20px 20px;
            box-sizing: border-box;
            .checkListAll {
              margin-top:20px;
              span {
                float: left;
                font-size: 14px;
                color: #262626;
              }
              .checkList {
                float: left;
                margin-left:20px;
              }
            }
            .checkListAll:first-child{
                 margin-top:12px;
            }
          }
      }
  }
  .mapContainer {
    float: left;
    width:80%;
    height:150px;
    position:relative;
    margin-left:100px;
    margin-top:10px;
    z-index:1;
  }
  #mapContainer {
    width:100%;
    height:150px;
  }
  .sumitAdd {
    padding:50px 50px 30px 0;
    box-sizing: border-box;
    .sumitBtn {
      float: left;
      width:180px;
      height: 50px;
      border:1px solid #DCDFE6;
      border-radius: 5px;
      -webkit-border-radius: 5px;
      text-align: center;
      line-height: 50px;
      margin-left:30px;
      cursor: pointer;
    }
    .setData {
      background: #FC612A;
      color: #fff;
      border:1px solid #FC612A;
      margin-left:360px;
    }
  }
  .uploadFontFont {
    float: left;
    height:40px;
    margin-left:10px;
    position: relative;
    p {
       font-size: 12px;
       color: #A9A9A9;
    }
    .xing {
      position: absolute;
      left:0;
      top:0;
      font-size: 16px;
      color: #F52D2D;
    }
  }
</style>